package com.zlt.util;

import java.io.*;

public class FileUtil {
    /**
     * 缓冲流拷贝文件
     * @param from
     * @param to
     * @throws FileNotFoundException
     */
    public static void bufferCopyFile(String from,String to) throws FileNotFoundException {
        File fromFile = new File(from);
        //判断文件是否存在
        if(!fromFile.exists()) {
            throw new FileNotFoundException(from + "文件不存在");
        }

        if(!fromFile.isFile()) {
            throw new RuntimeException(from + "不是文件");
        }
        File toFilePath = new File(to);

        if(!toFilePath.exists()) {
            toFilePath.mkdirs();//如果不存在就创建一个目录
        }

        if(!toFilePath.isDirectory()) {
            throw new RuntimeException(to + "不是目录");
        }
        //拷贝到的文件对象
        File toFile = new File(to, fromFile.getName());

        InputStream is = null;
        BufferedInputStream bis = null;
        OutputStream os = null;
        BufferedOutputStream bos = null;
        is = new FileInputStream(fromFile);
        bis = new BufferedInputStream(is);
        os = new FileOutputStream(toFile);
        bos = new BufferedOutputStream(os);
        byte [] bytes = new byte[1024];
        int len = 0;
        try {
            while((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
